<template>
  <div>
    <a-steps
      label-placement="vertical"
      :current="steps.current"
      :status="steps.status"
      @change="setCurrent"
    >
      <a-step>添加发送内容</a-step>
      <a-step>选择群发对像</a-step>
      <a-step>创建成功</a-step>
    </a-steps>
    <a-divider />
    <a-form
      ref="formRef"
      :rules="rules"
      :model="formData"
      auto-label-width
      @submit="handleSubmitForm"
    >
      <div v-if="steps.current === 1">
        <!-- 添加发送内容 单选-->
        <a-radio-group
          default-value="text"
          v-model="formData.msgtype"
          :options="[
            { label: '文本', value: 'text' },
            { label: '图片', value: 'image' },
            { label: '文件', value: 'file' },
            { label: '小程序', value: 'gh' },
            { label: '链接', value: 'share' },
          ]"
          @change="handleRadioChange"
        >
        </a-radio-group>
        <div style="margin-top: 16px; height: 200px">
          <div v-if="formData.msgtype === 'text'">
            <a-textarea
              style="height: 200px"
              v-model="formData.content"
              placeholder="输入群发文本"
              allow-clear
            />
          </div>
          <div v-if="formData.msgtype === 'image'">
            <a-input
              v-model="formData.path"
              placeholder="输入图片本地路径"
              allow-clear
            >
              <template #prepend> 本地图片路径 </template>
            </a-input>
            示例：e:\Users\Administrator\Desktop\群发内容\五星红旗.png
          </div>
          <div v-if="formData.msgtype === 'file'">
            <a-input
              v-model="formData.path"
              placeholder="输入文件本地路径"
              allow-clear
            >
              <template #prepend> 本地文件路径 </template>              
            </a-input>
            示例：e:\Users\Administrator\Desktop\群发内容\1.xlsx
          </div>
          <div v-if="formData.msgtype === 'gh'">
            <a-input v-model="formData.gh" placeholder="输入gh值" allow-clear>
              <template #prepend> gh </template>
            </a-input>
          </div>
          <div v-if="formData.msgtype === 'share'">
            <a-input v-model="formData.jumpUrl" placeholder="输入链接地址" allow-clear>
              <template #prepend> 网址 </template>
            </a-input>
          </div>
        </div>
      </div>
      <div v-if="steps.current === 2">
        <!-- 条件查询 -->
        <a-row :gutter="10" style="margin-bottom: 16px">
          <a-col :span="6"
            ><a-form-item field="nick" label="昵称">
              <a-input
                v-model="searchForm.nick"
                placeholder="请输入昵称"
                allow-clear
                @change="handleSearch"
              /> </a-form-item
          ></a-col>
          <a-col :span="6"
            ><a-form-item field="tags" label="标签">
              <a-input
                v-model="searchForm.tags"
                placeholder="请输入标签"
                allow-clear
                @change="handleSearch"
              /> </a-form-item
          ></a-col>
          <a-col :span="6"
            ><a-form-item field="isreceive" label="接收群发">
              <a-select
                v-model="searchForm.isreceive"
                placeholder="请选择"
                allow-clear
                @change="handleSearch"
              >
                <a-option :value="1">接收</a-option>
                <a-option :value="0">不接收</a-option>
              </a-select>
            </a-form-item></a-col
          >
          <a-col :span="4" style="text-align: right">
            <a-space>
              <a-button type="primary" @click="handleSearch">搜索</a-button>
              <a-button @click="handleReset">重置</a-button>
            </a-space>
          </a-col>
          <a-col :span="6">
            <a-space>
              <a-button
                type="primary"
                status="success"
                @click="handleIsreceive(1)"
                >全开</a-button
              >
              <a-button
                type="primary"
                status="warning"
                @click="handleIsreceive(0)"
                >全关</a-button
              >
            </a-space>
          </a-col>
        </a-row>
        <!-- 表格 -->
        <a-table
          row-key="wxid"
          :data="friendList"
          :columns="columns"
          :loading="loading"
          :pagination="{
            total: count,
            current: current,
            pageSize: pageSize,
            showTotal: true,
            showPageSize: true,
          }"
          :row-selection="{
            type: 'checkbox',
            showCheckedAll: true,
            onlyCurrent: false,
          }"
          v-model:selectedKeys="selectedKeys"
          @page-change="handlePageChange"
          @page-size-change="handlePageSizeChange"
        >
          <template #isreceive="{ record }">
            <a-switch
              v-model="record.isreceive"
              @change="(value) => handleSwitch(record.wxid, Boolean(value))"
            />
          </template>
          <template #tags="{ record }">
            <a-space wrap>
              <a-tag
                v-for="tag in record.tags"
                :key="tag"
                closable
                @close="handleRemoveTag(record, tag)"
              >
                {{ tag }}
              </a-tag>
              <a-input
                v-if="showInput && editingWxid === record.wxid"
                ref="inputRef"
                v-model="inputVal"
                :style="{ width: '90px' }"
                size="mini"
                @keyup.enter="handleAddTag(record)"
                @blur="handleAddTag(record)"
              />
              <a-tag
                v-else
                :style="{
                  backgroundColor: 'var(--color-fill-2)',
                  border: '1px dashed var(--color-fill-3)',
                  cursor: 'pointer',
                }"
                @click="handleEditTag(record)"
              >
                <template #icon>
                  <icon-plus />
                </template>
              </a-tag>
            </a-space>
          </template>
        </a-table>
      </div>
      <div v-if="steps.current === 3" style="text-align: center">
        <icon-check-circle :size="100" style="color: #23c343" />
      </div>
      <!-- 切换按钮 -->
      <div
        :style="{
          width: '100%',
          textAlign: 'center',
          background: 'var(--color-bg-2)',
          color: '#C2C7CC',
          marginTop: '50px',
        }"
      >
        <a-space size="large">
          <a-button
            type="secondary"
            :disabled="steps.current <= 1"
            @click="onPrev"
          >
            <IconLeft />返回
          </a-button>
          <a-button
            type="primary"
            v-if="steps.current === 1"
            @click="handleStep1"
            >下一步</a-button
          >
          <a-button type="primary" v-if="steps.current === 2" html-type="submit"
            >提交</a-button
          >
          <a-button
            type="primary"
            v-if="steps.current === 3"
            @click="handleCloseModal"
            >完成</a-button
          >
        </a-space>
      </div>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, nextTick } from 'vue';
  import { Message, TableColumnData } from '@arco-design/web-vue';
  import {
    getFriendList,
    editFriend,
    batchEditFriendSwitch
  } from '@/api/weixin';
  import { createFriendSendTask } from '@/api/task';

  const props = defineProps<{
    selectedWxid: string;
  }>();

  const emits = defineEmits(['closeModal']);
  const initialFromData = {
    ownerWxid: '',
    wxid: '',
    msgtype: 'text',
    content: '',
    jumpUrl: '',
    jumpPath: '',
    gh: '',
    appid: '',
    path: '',
    filename: '',
    musicUrl: '',
    imageUrl: '',
    triggerTime: '',
    status: 0,
  };
  const steps = reactive({
    current: 1,
    status: 'process' as 'wait' | 'error' | 'finish' | 'process',
  });
  const rules = {};
  const formData = reactive({ ...initialFromData });

  const columns: TableColumnData[] = [
    {
      title: '呢称',
      dataIndex: 'nick',
    },
    {
      title: 'wxid',
      dataIndex: 'wxid',
    },
    {
      title: '标签',
      slotName: 'tags',
    },
    {
      title: '群发开关',
      slotName: 'isreceive',
    },
  ];

  // 获取好友列表数据
  const friendList = ref([]);
  const selectedKeys = ref<string[]>([]);
  const current = ref(1);
  const pageSize = ref(10);
  const count = ref(0);
  const loading = ref(false);
  const searchForm = reactive({
    nick: '',
    tags: '',
    isreceive: undefined,
  });
  const fetchFriendList = async (wxid: string) => {
    loading.value = true;
    try {
      const res: any = await getFriendList(wxid, {
        field: {
          nick: searchForm.nick,
          tags: searchForm.tags,
          isreceive: searchForm.isreceive,
        },
        page: current.value,
        pageSize: pageSize.value,
      });
      if (res.code === 20000) {
        count.value = res.data.count;
        friendList.value = res.data.list;
      } else {
        Message.error(res.msg || '获取好友列表失败');
      }
    } catch (error) {
      console.error('获取好友列表失败:', error);
    } finally {
      loading.value = false;
    }
  };

  // 处理页码变化
  const handlePageChange = async (page: number) => {
    current.value = page;
    await fetchFriendList(props.selectedWxid);
  };
  // 处理每页条数变化
  const handlePageSizeChange = async (size: number) => {
    pageSize.value = size;
    current.value = 1; // 切换页面大小时重置为第一页
    await fetchFriendList(props.selectedWxid);
  };
  // 搜索处理
  const handleSearch = () => {
    current.value = 1; // 重置页码
    fetchFriendList(props.selectedWxid);
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.nick = '';
    searchForm.tags = '';
    searchForm.isreceive = undefined;
    selectedKeys.value = [];
    current.value = 1;
    fetchFriendList(props.selectedWxid);
  };

  // 群发开关
  const handleSwitch = async (friendwxid: string, value: boolean) => {
    try {
      const res: any = await editFriend({
        mywxid: props.selectedWxid,
        wxid: friendwxid,
        field: {
          isreceive: value ? 1 : 0,
        },
      });
      if (res.code === 20000) {
        Message.success('设置成功');
      } else {
        Message.error(res.msg || '设置失败');
      }
    } catch (error) {
      Message.error('设置失败');
    }
  };
  // 全开
  const handleIsreceive = async (number: number) => {
    try {
      const res: any = await batchEditFriendSwitch({
        mywxid: props.selectedWxid,
        field: {
          isreceive: number === 1 ? 1 : 0,
        },
      });
      if (res.code === 20000) {
        Message.success('设置成功');
        fetchFriendList(props.selectedWxid);
      } else {
        Message.error(res.msg || '设置失败');
      }
    } catch (error) {
      Message.error('设置失败');
    }
  };

  // 标签编辑相关变量
  const inputRef = ref<HTMLTextAreaElement | null>(null);
  const showInput = ref(false);
  const inputVal = ref('');
  const editingWxid = ref('');

  // 开始编辑标签
  const handleEditTag = (record: any) => {
    editingWxid.value = record.wxid;
    showInput.value = true;

    nextTick(() => {
      if (inputRef.value) {
        inputRef.value.focus();
      }
    });
  };
  // 添加标签
  const handleAddTag = async (record: any) => {
    if (inputVal.value) {
      try {
        // 获取当前标签数组
        const currentTags = [...(record.tags || [])];
        // 添加新标签
        if (!currentTags.includes(inputVal.value)) {
          currentTags.push(inputVal.value);

          const res: any = await editFriend({
            mywxid: props.selectedWxid,
            wxid: record.wxid,
            field: {
              tags: currentTags,
            },
          });

          if (res.code === 20000) {
            Message.success('添加标签成功');
            await fetchFriendList(props.selectedWxid);
          } else {
            Message.error(res.msg || '添加标签失败');
          }
        }
      } catch (error) {
        Message.error('添加标签失败');
      }
    }
    inputVal.value = '';
    showInput.value = false;
    editingWxid.value = '';
  };

  // 移除标签
  const handleRemoveTag = async (record: any, tag: string) => {
    try {
      const currentTags = record.tags.filter((t: string) => t !== tag);
      const res: any = await editFriend({
        mywxid: props.selectedWxid,
        wxid: record.wxid,
        field: {
          tags: currentTags,
        },
      });

      if (res.code === 20000) {
        Message.success('删除标签成功');
        await fetchFriendList(props.selectedWxid);
      } else {
        Message.error(res.msg || '删除标签失败');
      }
    } catch (error) {
      Message.error('删除标签失败');
    }
  };
  // 切换步条
  const setCurrent = (e: number) => {
    steps.current = e;
  };
  const onPrev = () => {
    // resetFormData();
    steps.current = Math.max(1, steps.current - 1);
  };

  // 选择发送内容
  const handleRadioChange = async (value: any) => {
    formData.msgtype = value;
    formData.content = '';
    formData.path = '';
    formData.jumpUrl = '';
    formData.jumpPath = '';
    formData.gh = '';
    formData.appid = '';
    formData.filename = '';
  };

  const handleStep1 = () => {
    // 群发内容不能为空
    if (
      formData.content === '' &&
      formData.path === '' &&
      formData.gh === '' &&
      formData.appid === '' &&
      formData.jumpUrl === ''
    ) {
      Message.warning('群发内容不能为空，请检查');
    } else {
      steps.current = Math.min(3, steps.current + 1);
      fetchFriendList(props.selectedWxid);
    }
  };
  const handleSubmitForm = async () => {
    formData.ownerWxid = props.selectedWxid;
    try {
      const res: any = await createFriendSendTask({
        formData
      });

      if (res.code === 20000) {
        Message.success('删除标签成功');
        steps.current = Math.min(3, steps.current + 1);
      } else {
        Message.error(res.msg || '删除标签失败');
      }
    } catch (error) {
      Message.error('删除标签失败');
    }
  };

  const handleCloseModal = () => {
    // 可以通过 emit 或者其他方式通知父组件
    steps.current = 1; // 重置步骤
    emits('closeModal');
  };
</script>
